<template>
  <!-- 职位管理 -->
  <div>
    <div>
      <h1>职位管理</h1>
    </div>
    <!-- 搜索容器 -->
    <div class="search-container">
      <!-- 行业输入框 -->
      <span class="search-label">职位类别：</span>
      <el-input
        v-model="typeName"
        placeholder="搜索职位类别"
        class="search-input search-industry"
        clearable
      >
      </el-input>

      <!-- 职位输入框 -->
      <span class="search-label">职位：</span>
      <el-input
        v-model="jobName"
        placeholder="搜索职位"
        class="search-input"
        clearable
      >
      </el-input>

      <!-- 状态下拉框（仅启用和禁用） -->
      <span class="search-label">状态：</span>
      <el-select
        v-model="jobStatus"
        placeholder="请选择状态"
        class="search-select"
      >
        <el-option
          v-for="item in options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        >
        </el-option>
      </el-select>

      <el-button type="primary" class="search-button" @click="handleSearch"
        >查询</el-button
      >
      <el-button type="success" class="search-button" @click="handleReset"
        >重置</el-button
      >
      <el-button type="success" class="search-button" @click="handleAdd"
        >添加职位</el-button
      >
    </div>

    <el-table
      :data="tableData"
      border
      style="width: 100%; margin-top: 15px"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      v-loading="dataLoading" element-loading-text="拼命加载中"
    >
      <!-- 第一列：行业 -->
      <el-table-column
        prop="jobTypeDO.typeName"
        label="职位类别"
      ></el-table-column>

      <!-- 第二列：职位 -->
      <el-table-column prop="jobName" label="职位"></el-table-column>

      <!-- 第三列：职位简介 -->
      <el-table-column prop="jobInfo" label="职位简介"></el-table-column>

      <!-- 第四列：状态列 -->
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.jobStatus === 0" type="success">启用</el-tag>
          <el-tag v-else-if="scope.row.jobStatus === 1" type="danger"
            >禁用</el-tag
          >
        </template>
      </el-table-column>

      <!-- 第五列：职位操作 -->
      <el-table-column label="职位操作" width="260">
        <template slot-scope="scope">
          <el-button @click="handleEdit(scope.row)" size="mini" type="primary">修改职位</el-button>
          <!-- <el-button @click="handleDelete(scope.row)" type="text" size="small">删除职位</el-button> -->
          <el-button v-if="scope.row.jobStatus == 0" size="mini" type="danger"
            @click="updateJobStatusHandler(scope.row)">禁用</el-button>
          <el-button v-if="scope.row.jobStatus == 1" size="mini" type="success"
            @click="updateJobStatusHandler(scope.row)">启用</el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 编辑职位弹窗 -->
    <el-dialog
      title="编辑职位"
      :visible.sync="editDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form :model="editData" label-width="100px">
        <el-form-item label="职位类别：">
          <el-input v-model="editData.typeName"></el-input>
        </el-form-item>

        <el-form-item label="职位：">
          <el-input v-model="editData.jobName"></el-input>
        </el-form-item>

        <el-form-item label="职位简介：">
          <el-input
            v-model="editData.jobInfo"
            type="textarea"
            :rows="4"
          ></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer">
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveEdit" :loading="isSaving"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 添加职位弹窗（带验证） -->
    <el-dialog
      title="添加职位"
      :visible.sync="addDialogVisible"
      width="500px"
      :close-on-click-modal="false"
    >
      <!-- 表单添加验证规则和引用 -->
      <el-form
        :model="addData"
        label-width="100px"
        :rules="formRules"
        ref="addFormRef"
      >
        <el-form-item label="职位类别：" prop="typeName">
          <el-input
            v-model="addData.typeName"
            placeholder="请输入职位类别"
          ></el-input>
        </el-form-item>
        <el-form-item label="职位：" prop="jobName">
          <el-input
            v-model="addData.jobName"
            placeholder="请输入职位名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="职位简介：" prop="jobInfo">
          <el-input
            v-model="addData.jobInfo"
            type="textarea"
            :rows="4"
            placeholder="请输入职位简介"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveAdd" :loading="isAdding"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 删除弹窗 -->
    <el-dialog
      title="删除职位"
      :visible.sync="deleteDialogVisible"
      width="420px"
      center
      class="delete-dialog"
    >
      <div class="delete-content">
        <div class="message-row">
          <i class="el-icon-warning warning-icon"></i>
          <div class="text-content">
            <p class="message">
              确定要删除
              <span class="course-name">{{ currentDeleteRow?.jobName }}</span>
              职位吗？
            </p>
            <p class="warning-message">此操作不可撤销！</p>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false" size="small"
          >取消</el-button
        >
        <el-button
          type="danger"
          @click="confirmDelete"
          size="small"
          icon="el-icon-delete"
          class="confirm-delete-btn"
          :loading="isDeleting"
        >
          确认删除
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { selectByJob, updateByJob, addByAdd, deleteJob } from "@/api/job";
export default {
  methods: {
    // 打开编辑弹窗并初始化数据
    handleEdit(row) {
      // 复制行数据到编辑对象，避免直接修改表格数据
      this.editData = {
        jobId: row.jobId,
        typeName: row.jobTypeDO.typeName,
        jobName: row.jobName,
        jobInfo: row.jobInfo,
      };
      this.editDialogVisible = true;
    },

    // 保存编辑
    async saveEdit() {
      try {
        this.isSaving = true;

        // 1. 调用API更新数据
        const response = await updateByJob(this.editData);

        if (response.code === 200) {
          console.log("-----" + response.data);

          // 2. 关闭弹窗并提示
          this.editDialogVisible = false;
          this.$message.success("职位信息更新成功");

          // 3. 重新查询数据库
          this.loadData({});
        } else {
          this.$message.error(
            `更新失败: ${response.data.message || "未知错误"}`
          );
        }
      } catch (error) {
        console.error("更新失败:", error);
        this.$message.error("更新失败，请重试");
      } finally {
        this.isSaving = false;
      }
    },

    updateJobStatusHandler(row) {
      this.$confirm(
        `此操作将修改职位为${row.jobName}的状态, 是否继续?`, // 优化文案：原“账号”改为“状态”更准确
        "温馨提示",
        {
          confirmButtonText: "确定修改",
          cancelButtonText: "取消修改",
          type: "warning" // 可选：添加弹窗类型，显示警告图标，体验更好
        }
      )
        .then(() => {
          const statusData = {
            jobId: row.jobId,
            jobStatus: row.jobStatus === 0 ? 1 : 0,
          };
          deleteJob(statusData).then((res) => {

            if (res.code == 200) {
              this.$message({
                type: "success",
                message: "状态修改成功",
              });
              this.handleSearch();
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消状态修改"
          });
        });
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.handleSearch();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.handleSearch();
    },

    // 带验证的保存方法
    async saveAdd() {
      // 触发表单验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (valid) {
          // 验证通过，执行保存逻辑
          try {
            this.isAdding = true;
            const response = await addByAdd(this.addData);

            if (response.code === 200) {
              this.addDialogVisible = false;
              this.$message.success("职位添加成功");
              this.loadData({});
              // 重置表单
              this.$refs.addFormRef.resetFields();
            } else {
              this.$message.error(
                `添加失败: ${response.data.message || "未知错误"}`
              );
            }
          } catch (error) {
            console.error("添加失败:", error);
            this.$message.error("添加失败，请重试");
          } finally {
            this.isAdding = false;
          }
        } else {
          // 验证失败，提示用户
          this.$message.warning("请填写所有必填字段");
          return false;
        }
      });
    },

    // 打开添加弹窗并初始化空数据
    handleAdd() {
      this.addData = {
        typeName: "",
        jobName: "",
        jobInfo: "",
      };
      this.addDialogVisible = true;
      // 新增：打开弹窗后重置表单验证状态
      this.$nextTick(() => {
        this.$refs.addFormRef?.resetFields();
      });
    },

    // 打开删除弹窗
    handleDelete(row) {
      this.currentDeleteRow = row; // 保存当前要删除的行数据
      this.deleteDialogVisible = true;
    },

    // 确认删除
    async confirmDelete() {
      try {
        const params = {
          jobId: this.currentDeleteRow.jobId, // 使用当前删除行的jobId
        };
        // 后续补充
        // 1. 调用删除接口
        this.isDeleting = true; // 添加载状态（需在data中定义）
        const response = await deleteJob(params);

        // 2. 处理接口响应
        if (response.code === 200) {
          console.log("****" + response);

          this.deleteDialogVisible = false; // 关闭删除弹窗

          this.$message.success("职位删除成功");
          this.loadData({}); // 重新加载表格数据，刷新列表
        } else {
          // 接口返回错误（如职位不存在、关联数据未删除等）
          this.$message.error(
            `删除失败: ${response.data?.message || "未知错误"}`
          );
        }
      } catch (error) {
        console.error("删除职位失败:", error);
        this.$message.error("删除职位失败，请检查网络连接或稍后重试");
      } finally {
        this.isDeleting = false; // 关闭加载状态
      }
    },

    // 查询按钮点击事件
    handleSearch() {
      const params = {
        typeName: this.typeName,
        jobName: this.jobName,
        jobStatus: this.jobStatus,

        currentPage: this.currentPage, //当前页
        pageSize: this.pageSize, //每页大小
      };
      this.loadData(params);
    },

    // 重置按钮点击事件
    // 重置按钮点击事件（仅修改这一个方法）
    handleReset() {
      // 1. 清空所有查询条件
      this.typeName = '';
      this.jobName = '';
      this.jobStatus = null; // 与data中初始值保持一致

      // 2. 重置分页到初始状态（第1页，每页5条）
      this.currentPage = 1;
      this.pageSize = 5;

      // 3. 直接调用原有的loadData({})，无需改其他地方
      this.loadData({});
    },

    // 加载数据方法
    // 加载数据方法（仅修改这一个方法）
    async loadData(params) {
      //开启加载动画
      this.dataLoading=true;
      try {
        // 关键：合并参数——传入的params优先级高，缺失则用组件当前的分页值
        const fullParams = Object.assign(
          {
            currentPage: this.currentPage, // 自动补充当前页码
            pageSize: this.pageSize        // 自动补充每页条数
          },
          params // 传入的查询条件（如typeName、jobName）会覆盖默认值（若有）
        );

        // 调用接口时传合并后的完整参数
        const response = await selectByJob(fullParams);
        this.tableData = response.data.list || [];
        this.total = response.data.total;
        //关闭加载动画
          this.dataLoading=false;
      } catch (error) {
        console.error("数据加载失败:", error);
        this.$message.error("加载数据失败，请稍后重试");
      }
    }

  },

  data() {
    return {
      //加载状态
      dataLoading:false,
      // 新增职位表单验证规则
      formRules: {
        typeName: [
          // 对应职位类别输入框（prop="typeName"）
          { required: true, message: "请输入职位类别", trigger: "blur" },
        ],
        jobName: [
          // 对应职位名称输入框（prop="jobName"）
          { required: true, message: "请输入职位名称", trigger: "blur" },
        ],
        jobInfo: [
          // 对应职位简介输入框（prop="jobInfo"）
          { required: true, message: "请输入职位简介", trigger: "blur" },
        ],
      },

      // 编辑弹窗相关
      editDialogVisible: false,
      editData: { jobId: null, typeName: "", jobName: "", jobInfo: "" },
      isSaving: false, // 保存按钮加载状态

      // 添加弹窗相关（新增）
      addDialogVisible: false, // 添加弹窗显示状态
      addData: { typeName: "", jobName: "", jobInfo: "" }, // 添加表单数据（空初始值）
      isAdding: false, // 添加按钮加载状态

      // 删除弹窗相关
      deleteDialogVisible: false,
      currentDeleteRow: null, // 当前要删除的行数据
      isDeleting: false, // 删除按钮加载状态

      // 搜索条件
      jobId: "",
      typeName: "",
      jobName: "",
      jobStatus: null,
      tableData: [],
      currentPage: 1, //当前页
      pageSize: 5, //每页大小
      total: 0,

      // 状态选项
      options: [
        { value: 0, label: "启用" },
        { value: 1, label: "禁用" },
      ],
    };
  },

  created() {
    this.handleSearch();
  },

}
</script>

<style scoped>
.search-container {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 0;
}

.search-label {
  white-space: nowrap;
  font-size: 14px;
  color: #606266;
  margin-right: 0;
}

.search-input {
  width: 160px;
  margin-right: 8px;
}

.search-select {
  width: 160px;
  margin-right: 8px;
}

.search-button {
  margin-left: 8px;
}

.el-table th {
  height: 70px !important;
  line-height: 70px !important;
}

.el-table {
  margin-top: 15px;
}

.el-table__header-wrapper th {
  background-color: #f5f7fa;
}

.pagination-left {
  margin-top: 15px;
  text-align: left;
}

.el-table .el-button--text {
  margin: 0 5px;
}

/* 删除弹窗样式 */
.delete-dialog .message-row {
  display: flex;
  align-items: center;
}

.delete-dialog .warning-icon {
  color: #faad14;
  margin-right: 8px;
  font-size: 30px;
}

.delete-dialog .text-content {
  flex: 1;
}

.delete-dialog .message {
  margin: 0 0 8px 0;
  line-height: 1.5;
}

.delete-dialog .warning-message {
  margin: 0;
  color: #f56c6c;
  line-height: 1.5;
}

.course-name {
  color: #1890ff;
  font-weight: bold;
}
</style>